package com.vertx.verticles;

import io.vertx.core.AbstractVerticle;
import io.vertx.redis.client.*;

/**
 * @name: RedisVerticle
 * @description: RedisVerticle
 * @author: jiangcs
 */
public class RedisVerticle extends AbstractVerticle {

    @Override
    public void start() throws Exception {
//        getAndSet();

        pubAndSub();
    }

    private void getAndSet() {
        RedisOptions redisOptions = new RedisOptions();
        redisOptions.setConnectionString("redis://:qdhlm.@192.168.0.158");
        Redis client = Redis.createClient(vertx, redisOptions);
        client.connect()
                .onSuccess((conn) -> {
                    System.out.println("connect server ok: 1");
                });
        RedisAPI api = RedisAPI.api(client);
        api.get("redis_test")
                .onSuccess((rsp) -> {
                    if (null != rsp) {
                        System.out.println("1:" + rsp.toString());
                    } else {
                        System.err.println("1: rsp is null");
                    }
                });
        api.setnx("redis_test", "ok")
                .onSuccess((rsp) -> {
                    System.out.println("2:" + rsp.toString());
                });
        api.get("redis_test")
                .onSuccess((rsp) -> {
                    if (null != rsp) {
                        System.out.println("3:" + rsp.toString());
                    } else {
                        System.err.println("3: rsp is null");
                    }
                });
    }

    private void pubAndSub() {
        RedisOptions redisOptions = new RedisOptions();
        redisOptions.setConnectionString("redis://:qdhlm.@192.168.0.158");
        redisOptions.setRole(RedisRole.MASTER);
        Redis client = Redis.createClient(vertx, redisOptions);
        client.connect()
                .onSuccess((conn) -> {
                    System.out.println("connect server ok: 2");

                    conn.handler((message) -> {
                        System.out.println("handler message: " + message);
                    });
                });

        client.send(Request.cmd(Command.SUBSCRIBE).arg("channel"))
                .onSuccess((rsp) -> {
                    if (null != rsp) {
                        System.out.println("1:" + rsp);
                    } else {
                        System.err.println("1: rsp is null");
                    }
                })
                .onFailure(Throwable::printStackTrace);
        client.send(Request.cmd(Command.PUBLISH).arg("channel").arg("hello"))
                .onSuccess((rsp) -> {
                    if (null != rsp) {
                        System.out.println("2:" + rsp);
                    } else {
                        System.err.println("2: rsp is null");
                    }
                })
                .onFailure(Throwable::printStackTrace);
    }
}
